package com.sifeng.test;

import com.sifeng.pojo.BaseWorkload;
import com.sifeng.pojo.DevelopmentRequirementsScheduleDO;
import com.sifeng.utils.MyUtils;
import org.apache.commons.io.FileUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by yang_gsh on 2018/9/11.
 * 创建复评材料
 */
public class NewCreateReappraisalMaterials {
    /**
     * 修改成当月
     */
    private static String date = "201911";
    private static String basePath = "E:\\hisun\\开发三部\\功能点评估表\\";
    private static String path = basePath + date  + "\\";
    /**
     * 修改月份
     */
    private static String reappraisalMaterialsPath = path + "11月开发复评材料-杨贵生1\\";
    private static String listFilePath = path + "开发需求明细表（11月）.xlsx";

    private static int finishThisMonthNum = 0;

    private static String thisDepartment = "营销服务研发部";



    public static void copyFile(String sourcePath, String dstPath) {
        try {
            FileUtils.copyFile(new File(sourcePath), new File(dstPath));
        } catch (IOException e) {
            System.out.println(sourcePath + "not found : " + e.getMessage());
        }

    }

    public static List<DevelopmentRequirementsScheduleDO> getDemandList(String path) throws IOException {
        XSSFWorkbook wb = MyUtils.getXSSFWorkbook(path);
        XSSFSheet sheet = wb.getSheetAt(0);
        List<DevelopmentRequirementsScheduleDO> list = new ArrayList<DevelopmentRequirementsScheduleDO>();
        if (sheet == null) {
            return null;
        }

        for(int i = 1; i <= sheet.getLastRowNum(); i++) {
            XSSFRow row = sheet.getRow(i);
            XSSFCell cellA = row.getCell(4);
            if(cellA == null) {
                continue;
            }
            String demandInternalNumber = cellA.getStringCellValue();

            if("".equals(demandInternalNumber.trim())) {
                continue;
            }

            DevelopmentRequirementsScheduleDO developmentRequirementsScheduleDO = new DevelopmentRequirementsScheduleDO();
            developmentRequirementsScheduleDO.setSerialNumber(demandInternalNumber.trim());
            developmentRequirementsScheduleDO.setHisunLeadingDepartment(row.getCell(1).getStringCellValue());
            developmentRequirementsScheduleDO.setProductName(row.getCell(2).getStringCellValue());
            developmentRequirementsScheduleDO.setRequirementName(row.getCell(3).getStringCellValue());
            developmentRequirementsScheduleDO.setRequirementNumber(row.getCell(4).getStringCellValue());
            developmentRequirementsScheduleDO.setEstimatedWorkload(Double.valueOf(row.getCell(6).getNumericCellValue()).intValue());
            developmentRequirementsScheduleDO.setFinallyWorkload(Double.valueOf(row.getCell(7).getNumericCellValue()).intValue());

            list.add(developmentRequirementsScheduleDO);
        }

        return list;
    }

    public static Map<String, Integer> moveFile(String demandNumber, String demandName, String resourcePath) {

        String preFileNameTmp =  demandNumber + "_" + demandName;
        File reappraisalMaterialsReqFile = new File(reappraisalMaterialsPath + preFileNameTmp);
        if(!reappraisalMaterialsReqFile.exists()){
            //如果文件夹不存在
            reappraisalMaterialsReqFile.mkdir();//创建文件夹
        }

        List<String> technicalProposalSpecificationList = MyUtils.searchFile(resourcePath, demandNumber, "_技术方案说明书", ".docx");
        for (String s : technicalProposalSpecificationList) {
            NewCreateReappraisalMaterials.copyFile(resourcePath + s,reappraisalMaterialsPath + preFileNameTmp + "\\" + s);
        }

        List<String> atomicFunctionPointList = MyUtils.searchFile(resourcePath, demandNumber, "_原子功能点评估表(电子工单)", ".xlsx");
        for (String s : atomicFunctionPointList) {
            NewCreateReappraisalMaterials.copyFile(resourcePath + s, reappraisalMaterialsPath + preFileNameTmp + "\\" + s);
        }

        List<String>  requirementsSpecificationList = MyUtils.searchFile(resourcePath, demandNumber, "需求方案说明书", null);
        for (String s : requirementsSpecificationList) {
            NewCreateReappraisalMaterials.copyFile(resourcePath + s, reappraisalMaterialsPath + preFileNameTmp + "\\" + s);
        }

        List<String>  requirementsSpecificationList1 = MyUtils.searchFile(resourcePath, demandNumber, "需求说明书", null);
        for (String s : requirementsSpecificationList1) {
            NewCreateReappraisalMaterials.copyFile(resourcePath + s, reappraisalMaterialsPath + preFileNameTmp + "\\" + s);
        }

        Map<String, Integer> map = new HashMap<>(3);
        map.put("technicalProposalSpecificationList", technicalProposalSpecificationList.size());
        map.put("atomicFunctionPointList", atomicFunctionPointList.size());
        map.put("requirementsSpecificationList", requirementsSpecificationList.size() + requirementsSpecificationList1.size());

        return map;
    }

    public static void fetchList(List<DevelopmentRequirementsScheduleDO> list) {
        list.forEach(developmentRequirementsScheduleDO -> {
            if(thisDepartment.equals(developmentRequirementsScheduleDO.getHisunLeadingDepartment().trim())) {
                DateFormat dateFormat = new SimpleDateFormat("yyyyMM");
                Date targetDate;
                Date minimumDate;
                try {
                    targetDate = dateFormat.parse(date);
                    minimumDate = dateFormat.parse(developmentRequirementsScheduleDO.getRequirementNumber().trim().substring(4,10));
                } catch (ParseException e) {
                    e.printStackTrace();
                    System.out.println(developmentRequirementsScheduleDO.getRequirementNumber() + " date error!!");
                    return;
                }
                while (targetDate.compareTo(minimumDate) >= 0) {
                    String resourcePath = basePath + dateFormat.format(targetDate) + "\\";
                    Map<String, Integer> stringIntegerMap = moveFile(developmentRequirementsScheduleDO.getRequirementNumber(),
                            developmentRequirementsScheduleDO.getRequirementName(), resourcePath);
                    if(stringIntegerMap.get("technicalProposalSpecificationList") != 0 ||
                            stringIntegerMap.get("atomicFunctionPointList") != 0 ||
                            stringIntegerMap.get("requirementsSpecificationList") != 0) {
                        printNotFound(developmentRequirementsScheduleDO.getRequirementNumber() + "_" + developmentRequirementsScheduleDO.getRequirementName(),
                                stringIntegerMap.get("technicalProposalSpecificationList"),
                                stringIntegerMap.get("atomicFunctionPointList"),
                                stringIntegerMap.get("requirementsSpecificationList"));
                        finishThisMonthNum++;
                        break;
                    } else {
                        targetDate = monthAddNum(targetDate, -1);
                    }
                }
            }
        });

    }

    public static void printNotFound(String requirement, int technicalProposalSpecificationListSize, int atomicFunctionPointListSize, int requirementsSpecificationListSize) {
        String printStr = requirement + "：";
        if(technicalProposalSpecificationListSize == 0 || atomicFunctionPointListSize == 0 || requirementsSpecificationListSize == 0) {
            if(technicalProposalSpecificationListSize == 0) {
                printStr += "-技术方案未找到";
            }

            if(atomicFunctionPointListSize == 0) {
                printStr += "-原子功能点未找到";
            }

            if(requirementsSpecificationListSize == 0) {
                printStr += "-需求说明书未找到";
            }
        } else {
            printStr += "已完成复制";
        }

        System.out.println(printStr);
    }

    /**
     *
     * @param time
     *           时间
     * @param num
     *           加的数，-num就是减去
     * @return
     *          减去相应的数量的月份的日期
     * @throws ParseException Date
     */
    public static Date monthAddNum(Date time, Integer num){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(time);
        calendar.add(Calendar.MONTH, num);
        Date newTime = calendar.getTime();
        return newTime;
    }


    public static void main(String[] args) throws Exception {
        File reappraisalMaterialsfile = new File(reappraisalMaterialsPath);
        if(!reappraisalMaterialsfile.exists()){
            //如果文件夹不存在
            reappraisalMaterialsfile.mkdir();//创建文件夹
        }

        List<DevelopmentRequirementsScheduleDO> list = NewCreateReappraisalMaterials.getDemandList(listFilePath);

        NewCreateReappraisalMaterials.fetchList(list);

        System.out.println("总需求数：" + list.size());
        System.out.println("完成需求数：" + finishThisMonthNum);


    }
}
